package com.atguigu.gmall.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.util.HttpClientUtil;
import com.atguigu.gmall.item.client.ItemServiceClient;
import com.atguigu.gmall.model.cart.CartInfo;
import com.atguigu.gmall.model.enums.OrderStatus;
import com.atguigu.gmall.model.enums.ProcessStatus;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.order.mapper.CartInfoMapper;
import com.atguigu.gmall.order.mapper.OrderDetailMapper;
import com.atguigu.gmall.order.mapper.OrderInfoMapper;
import com.atguigu.gmall.order.service.OrderInfoService;
import com.atguigu.gmall.rebbit.constant.MqConst;
import com.atguigu.gmall.rebbit.service.RabbitService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class OrderInfoServiceImpl implements OrderInfoService {
    @Autowired
    private ItemServiceClient itemServiceClient;

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private CartInfoMapper cartInfoMapper;

    @Autowired
    private RabbitService rabbitService;

    @Value("${ware.url}")
    private String url;
    //提交订单
    @Override
    public Long submitOrder(OrderInfo orderInfo) {
        //保存订单
        //总金额
        //遍历价格，重新加载
        StringBuilder sb=new StringBuilder();//订单描述
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        orderDetailList.stream().forEach(orderDetail -> {
            orderDetail.setOrderPrice(itemServiceClient.getSkuPrice(orderDetail.getSkuId()));
            sb.append(orderDetail.getSkuNum()+" ");
        });
        orderInfo.setOrderDetailList(orderDetailList);
        orderInfo.sumTotalAmount();
        //订单状态
         orderInfo.setOrderStatus(OrderStatus.UNPAID.name());
        //订单交易编号
        String outTradeNo="ATGUIGU"+System.currentTimeMillis()+new Random().nextInt(1000);
        orderInfo.setOutTradeNo(outTradeNo);
        //订单描述
        if(sb!=null&&sb.length()>100){
            orderInfo.setTradeBody(sb.toString().substring(100));
        }else {
            orderInfo.setTradeBody(sb.toString());
        }
        //创建时间
        Calendar calendar = Calendar.getInstance();
        orderInfo.setCreateTime(calendar.getTime());
        //失效时间
        calendar.add(Calendar.MINUTE,30);
        orderInfo.setExpireTime(calendar.getTime());
        //进程状态
        orderInfo.setProcessStatus(ProcessStatus.UNPAID.name());
        //保存
        orderInfoMapper.insert(orderInfo);
        //订单详情表
        List<OrderDetail> orderDetailList1 = orderInfo.getOrderDetailList();
        String redisKey = RedisConst.SECKILL_ORDERS + orderInfo.getUserId() + RedisConst.USER_CART_KEY_SUFFIX;
        List<String> redisDleteList=new ArrayList<>();
        orderDetailList1.forEach(orderDetail -> {
            //
            orderDetail.setOrderId(orderInfo.getId());
            orderDetailMapper.insert(orderDetail);
            redisDleteList.add(orderDetail.getSkuId().toString());
            cartInfoMapper.delete(new QueryWrapper<CartInfo>().eq("user_id",orderInfo.getUserId()).eq("sku_id",orderDetail.getSkuId()));
        });
        redisTemplate.opsForHash().delete(redisKey,redisDleteList.toArray());

        //rabbitmq删除订单，标记为已关闭
        rabbitService.sendDeadLetterMapper(MqConst.EXCHANGE_DIRECT_ORDER_CANCEL,MqConst.ROUTING_ORDER_CANCEL,orderInfo.getId(),MqConst.DELAY_TIME*10);
        return orderInfo.getId();
    }

    //连接库存，校验库存是否充裕
    @Override
    public boolean hasStock(Long skuId, Integer skuNum) {
        //HttpClient java代码写的一个类似于浏览器发送的请求， 响应， Http协议
        String urls=url+"/hasStock?skuId="+skuId+"&num="+skuNum;
        //封装类 ，响应
        return "1".equals(HttpClientUtil.doGet(urls));
    }

    //设置已关闭
    @Override
    public void cancelOrder(Long orderId, String uuid) {
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        if(orderInfo!=null){
            if(orderInfo.getOrderStatus().equals(OrderStatus.UNPAID.name())){
                orderInfo.setOrderStatus(OrderStatus.CLOSED.name());
                orderInfo.setProcessStatus(ProcessStatus.CLOSED.name());
                orderInfoMapper.updateById(orderInfo);
                System.out.println("取消订单成功"+new Date());
            }
        }
    }

    //获取订单信息
    @Override
    public OrderInfo getOrderInfo(Long orderId) {
        return orderInfoMapper.selectById(orderId);
    }

    //更新订单
    @Override
    public void updateOrderStatus(Long orderId, ProcessStatus paid) {
        System.out.println("异步回调更新订单");
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setId(orderId);
        orderInfo.setOrderStatus(paid.getOrderStatus().name());
        orderInfo.setProcessStatus(paid.name());
        orderInfoMapper.updateById(orderInfo);
    }

    //发送消息，通知仓库
    @Override
    public void sendOrderStatus(Long orderId) {
        System.out.println("异步回调，通知仓库");
        //更新状态
        updateOrderStatus(orderId,ProcessStatus.NOTIFIED_WARE);
        //根据id查询订单数据
        OrderInfo orderInfo = getOrderInfo(orderId);
        List<OrderDetail> order_id = orderDetailMapper.selectList(new QueryWrapper<OrderDetail>().eq("order_id", orderId));
        orderInfo.setOrderDetailList(order_id);
        //组织数据
        Map<String,Object> resultMap=initWareOrder(orderInfo);
        //通知仓库
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_WARE_STOCK,
                MqConst.ROUTING_WARE_STOCK, JSONObject.toJSONString(resultMap));


    }

    private Map<String, Object> initWareOrder(OrderInfo orderInfo) {
        Map<String,Object> resultMap = new HashMap<>();

        resultMap.put("orderId",orderInfo.getId());
        resultMap.put("consignee",orderInfo.getConsignee());
        resultMap.put("consigneeTel",orderInfo.getConsigneeTel());
        resultMap.put("orderComment",orderInfo.getOrderComment());
        resultMap.put("orderBody",orderInfo.getTradeBody());
        resultMap.put("deliveryAddress",orderInfo.getDeliveryAddress());
        resultMap.put("paymentWay","ONLINE".equals(orderInfo.getPaymentWay())?"2":"1");
        //订单详情
        List<Map> details = orderInfo.getOrderDetailList().stream().map(orderDetail -> {
            Map map = new HashMap();
            map.put("skuId", orderDetail.getSkuId());
            map.put("skuName", orderDetail.getSkuName());
            map.put("skuNum", orderDetail.getSkuNum());
            return map;
        }).collect(Collectors.toList());
        resultMap.put("details",details);
        return resultMap;
    }

    //拆单
    @Override
    public List<Map<String,Object>> orderSplit(Long orderId, String wareSkuMap) {
        //仓库获取的信息
        List<Map> mapList = JSONObject.parseArray(wareSkuMap,Map.class);
        OrderInfo orderInfoOrigin = getOrderInfo(orderId);
        List<OrderDetail> order_id = orderDetailMapper.selectList(new QueryWrapper<OrderDetail>().eq("order_id", orderId));
        orderInfoOrigin.setOrderDetailList(order_id);
        List<Map<String, Object>> listMap = mapList.stream().map(map -> {
            //创建类进行添加子订单
            OrderInfo subOrderInfo = new OrderInfo();
            //克隆
            BeanUtils.copyProperties(subOrderInfo, orderInfoOrigin);
            //id制空
            subOrderInfo.setId(null);
            //设置父Id
            subOrderInfo.setParentOrderId(orderInfoOrigin.getId());
            //获取子订单的详情
            List<String> skuIds = (List<String>) map.get("skuIds");
            List<OrderDetail> subOrderDetail = new ArrayList<>();
            for (String skuId : skuIds) {
                for (OrderDetail detailOrder : order_id) {
                    if (skuId.equals(detailOrder.getSkuId().toString())) {
                        subOrderDetail.add(detailOrder);
                        break;
                    }
                }
            }
            //将子订单详情添加到分表订单中
            subOrderInfo.setOrderDetailList(subOrderDetail);
            //计算总金额
            subOrderInfo.sumTotalAmount();
            orderInfoMapper.insert(subOrderInfo);
            subOrderInfo.getOrderDetailList().forEach(orderDetail -> {
                orderDetail.setOrderId(subOrderInfo.getId());
                orderDetailMapper.updateById(orderDetail);
            });
            return initWareOrder(subOrderInfo);
        }).collect(Collectors.toList());

        return listMap;
    }
}

